<template>
  <view>
    <div
      class="music-box"
      :class="{ animations: audioStatus }"
      @click="openAudio"
      v-if="questionnaireType === '1'"
    >
      <img src="@/static/music.png" alt="" />
    </div>
    <view class="full-container" v-if="pageType === -1">
      <u-empty mode="data" :text="text" />
    </view>
    <template v-if="pageType === 0 || pageType === 1">
      <view class="container" v-if="surveyQuestionList.length">
        <view class="bg-content">
          <image
            class="bg-content-img"
            src="../../static/bg.jpg"
            mode="widthFix"
          ></image>
          <view class="bg-content-shade"></view>
        </view>

        <u--form
          class="form-content"
          labelPosition="top"
          labelWidth="auto"
          :model="form"
          ref="form"
        >
          <view class="form-content-title">
            <u--text
              type="primary"
              size="48rpx"
              bold
              align="center"
              :text="title"
            ></u--text>
          </view>
          <div class="form-content-describe">{{ describe }}</div>
          <view class="form-item-content">
            <u-form-item
              :class="{ required: item.mustFlag === '0' }"
              :label="`${index + 1}. ${item.questionDescribe}`"
              :prop="item.id"
              v-for="(item, index) in surveyQuestionList"
              :key="item.id"
            >
              <u--textarea
                v-model="form[item.id]"
                :placeholder="`请输入${item.questionDescribe}`"
                v-if="item.inputType == '0'"
              ></u--textarea>
              <u-radio-group
                v-model="form[item.id]"
                placement="column"
                v-else-if="item.inputType == '1'"
              >
                <u-radio
                  :customStyle="{ marginBottom: '30rpx' }"
                  v-for="(sItem, sIndex) in item.surveyQuestionOptionList"
                  :key="sItem.id"
                  :label="sItem.description"
                  :name="sIndex + 1 + ''"
                >
                </u-radio>
              </u-radio-group>
              <u-checkbox-group
                v-model="form[item.id]"
                placement="column"
                v-else-if="item.inputType == '2'"
              >
                <u-checkbox
                  :customStyle="{ marginBottom: '30rpx' }"
                  v-for="(sItem, sIndex) in item.surveyQuestionOptionList"
                  :key="sItem.id"
                  :label="sItem.description"
                  :name="sIndex + 1 + ''"
                >
                </u-checkbox>
              </u-checkbox-group>
              <u--input
                v-model="form[item.id]"
                :placeholder="`请输入${item.questionDescribe}`"
                v-else-if="item.inputType == '4'"
              ></u--input>
            </u-form-item>
            <view class="" style="margin-top: 30rpx; margin-bottom: 30rpx">
              <u-button type="primary" @click="check">提交</u-button>
            </view>
          </view>
        </u--form>
      </view>
    </template>

    <!-- :class="{ bgf: questionnaireType === '1' }" -->
    <view class="full-container bgf" v-if="pageType === 2 || pageType === 3">
      <view class="answer-success" v-if="questionnaireType === '1'">
        <div class="cash-bg">
          <img class="cash-bg-img" src="@/static/cash-bg.png" alt="" />
          <div class="cash">￥{{ cashValue }}</div>
        </div>
        <view class="venue-number">编号：{{ venueNumber }}</view>
        <!-- <u-icon name="checkbox-mark" color="#5ac725" size="90"></u-icon> -->
        <view class="tip"
          >恭喜您，获得{{ cashValue }}元现金奖，根据编号兑奖！</view
        ><view class="tip line-down" @click="previewImage">查看活动行程！</view>
      </view>
      <div class="answer-success" v-else>
        <u-icon size="130" name="checkmark-circle" color="#13ce66"></u-icon>
        <view class="tip-success">问卷已提交！感谢您的参与</view>
        <view class="venue-number">编号：{{ venueNumber }}</view>
      </div>
    </view>
    <lottery ref="lotteryRef" @success="lotteryConfirm"></lottery>
    <div class="preview-image-box" v-show="showPreviewImage">
      <div class="clear-icon" @click="closePreviewImage" v-if="pageType !== 1">
        <icon type="clear" size="28" />
      </div>
      <div
        class="mask"
        :class="{ block: pageType === 1 }"
        @click="closePreviewImage"
      ></div>
      <div class="preview-image">
        <img :src="$imagePath + explainImage" alt="" />
      </div>
      <div class="next" @click="nextClick" v-if="pageType === 1">我知道了</div>
    </div>
  </view>
</template>

<script>
import { getUrlParam } from "../../utils/index.js";
import lottery from "@/components/lottery-turn.vue";
export default {
  components: { lottery },
  data() {
    return {
      title: "",
      describe: "",
      appid: "wx990d3f98fa758929",
      surveyQuestionList: [],
      form: {},
      rules: {},
      params: {
        bizSurveyId: "",
        osType: "0",
        openId: "",
        replyMap: {},
      },
      questionnaireType: "0", //问卷类型，0-问卷，1-邀请函
      isFail: 0, //0-待填写，1已完成
      pageType: 0, //-1,加载中/报错，0-待填写，1展示行程安排，2抽奖，3展示编号
      text: "获取题目中，请稍后",
      venueNumber: "", // 已填过问卷的场次号
      cashValue: 0,
      explainImage: "", //问卷图片
      showPreviewImage: false,
      audioContent: null, //音频
      audioStatus: false,
    };
  },
  onLoad(opt) {
    uni.setNavigationBarTitle({ title: "通立电梯" });
    const openid = uni.getStorageSync("openid");
    const code = getUrlParam("code");
    const surveyId = getUrlParam("surveyId");
    this.pageType = -1;
    if (openid) {
      this.params.openId = openid;
      this.params.bizSurveyId = surveyId;
      this.init();
    } else if (!code) {
      this.authLogin();
    } else {
      this.params.bizSurveyId = surveyId;
      this.$http("/elevator/wechat/auth/fixAuth", "post", {
        appid: this.appid,
        code: code,
      }).then(({ data }) => {
        this.params.openId = data.openid;
        uni.setStorageSync("openid", data.openid);
        this.init();
      });
    }
    // this.init()
  },
  methods: {
    onClick() {
      if (this.questionnaireType !== "1") return;
      this.audioContent.play();
    },
    initAudio() {
      if (this.questionnaireType !== "1") return;
      this.audioStatus = false;
      this.audioContent = uni.createInnerAudioContext();
      this.audioContent.src = "../../static/test.mp3";
      this.audioContent.loop = true;
      this.audioContent.onPlay(() => {
        console.log("播放成功");
        this.audioStatus = true;
      });
      this.audioContent.onStop(() => {
        console.log("播放停止");
        this.audioStatus = false;
      });
      this.audioContent.onPause(() => {
        console.log("播放暂停");
        this.audioStatus = false;
      });
      this.audioContent.onError((err) => {
        console.log("播放错误", err);
      });
      this.audioContent.play();
    },
    openAudio() {
      if (this.questionnaireType !== "1") return;
      this.audioStatus = !this.audioStatus;
      if (this.audioContent) {
        if (!this.audioStatus) {
          this.audioContent.pause();
        } else {
          this.audioContent.play();
        }
      }
    },
    // 抽奖结果
    lotteryConfirm(index, name) {
      this.cashValue = 100;
      this.pageType = 3;
    },
    authLogin() {
      let baseurl =
        process.env.NODE_ENV === "development"
          ? "http://survey.tldt.net" + location.search
          : location.href;
      let redirect_uri = encodeURIComponent(baseurl);
      var path = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=3#wechat_redirect`;
      window.location.href = path;
    },
    init() {
      // this.venueNumber = ''
      // this.surveyQuestionList = []
      this.$http("/elevator/survey/getInfo", "get", {
        id: this.params.bizSurveyId,
        openId: this.params.openId,
      })
        .then((res) => {
          const data = res.data;
          this.questionnaireType = data.type;
          this.initAudio();
          if (data.id) {
            this.pageType = 0;
            const { title, description, surveyQuestionList, id, type } = data;

            if (surveyQuestionList.length) {
              let isRules = false;
              this.title = title;
              this.describe = description;
              this.surveyQuestionList = surveyQuestionList;
              surveyQuestionList.forEach((item) => {
                this.$set(this.form, item.id, null);
                if (item.mustFlag === "0") {
                  this.$set(this.rules, item.id, [
                    {
                      // 自定义验证函数，见上说明
                      validator: (rule, value, callback) => {
                        let flag = false;
                        if (value) {
                          if (typeof value === "object") {
                            if (value.length) flag = true;
                          } else {
                            flag = true;
                          }
                        }
                        return flag;
                      },
                      message: `请${
                        (["0", "4"].includes(item.inputType)
                          ? "输入"
                          : "选择") + item.questionDescribe
                      }`,
                      // 触发器可以同时用blur和change
                      trigger: ["change", "blur"],
                    },
                  ]);
                  if (!isRules) isRules = true;
                }
              });
              this.$nextTick(() => {
                this.$refs.form.setRules(this.rules);
              });
            } else {
              this.initFail("获取题目失败");
            }
          } else {
            if (this.pageType === -1) {
              this.pageType = 3;
            }
            this.cashValue = 100;
          }
          this.venueNumber = data.code;
          this.explainImage = data.explainImage || "";
        })
        .catch((err) => {
          this.initFail(err.msg || "获取题目失败");
        });
    },
    initFail(msg) {
      this.text = msg;
      this.pageType = -1;
    },
    check() {
      if (Object.keys(this.rules).length) {
        this.$refs.form.validate().then((res) => {
          this.submit();
        });
      } else {
        this.submit();
      }
    },
    submit() {
      uni.showLoading({
        title: "加载中...",
      });
      let replyMap = {};
      Object.keys(this.form).forEach((field) => {
        const value = this.form[field];
        if (value && typeof value === "object") {
          replyMap[field] = value.join(",");
        } else {
          replyMap[field] = this.form[field];
        }
      });
      this.$http(`/elevator/survey-info/submit`, "post", {
        ...this.params,
        replyMap,
      })
        .then((res) => {
          uni.showToast({
            title: "提交成功",
            icon: "success",
            mask: true,
          });
          if (this.questionnaireType === "1") {
            this.audioContent.play();
            this.pageType = 1;
            this.previewImage();
          } else {
            this.pageType = 3;
          }
          //   setTimeout(() => {
          //     location.reload();
          //   }, 600);
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    previewImage() {
      this.showPreviewImage = true;
      // uni.previewImage({
      //   urls: [this.$imagePath + this.explainImage],
      // });
    },
    closePreviewImage() {
      if (this.pageType === 1) return;
      this.showPreviewImage = false;
    },
    nextClick() {
      this.pageType = 2;
      this.$refs.lotteryRef.open();
      this.init();
      this.closePreviewImage();
    },
  },
  onHide() {
    if (this.audioContent) {
      this.audioContent.stop();
      this.audioContent.destroy();
    }
  },
};
</script>

<style lang="scss" scoped>
page {
  background: #f3f4f5;
}

::v-deep .u-form-item {
  position: relative;

  .u-form-item__body__left__content__label {
    font-size: 32rpx;
    position: relative;
  }

  &.required .u-form-item__body__left__content__label {
    &:before {
      content: "*";
      color: #f56c6c;
      position: absolute;
      left: -20rpx;
    }
  }

  .u-form-item__body__right__message {
    position: absolute;
    left: 0;
    bottom: 0;
  }
}

::v-deep .u-radio-group {
  margin-top: 30rpx;
}

::v-deep .u-checkbox-group {
  margin-top: 30rpx;
}

::v-deep .u-textarea {
  margin-bottom: 30rpx;
}

::v-deep .u-input {
  margin-bottom: 30rpx;
}

.container {
  padding: 80rpx 0 28rpx;
  position: relative;

  .bg-content {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;

    .bg-content-img {
      width: 100%;
      height: auto;
      display: block;
    }

    .bg-content-shade {
      height: 160rpx;
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      background-image: linear-gradient(
        180deg,
        rgba(255, 255, 255, 0) 0%,
        #f4f7f9 100%
      );
    }
  }

  .form-content {
    position: relative;
    margin: 0 28rpx;
    background: #fff;

    .form-content-title {
      padding: 80rpx 36rpx 36rpx;
      line-height: 64rpx;
      font-weight: 600;
      text-align: center;
    }

    .form-content-describe {
      padding: 10rpx 36rpx 36rpx;
      font-size: 15px;
      line-height: 24px;
      text-align: justify;
      white-space: pre-wrap;
    }

    .form-item-content {
      padding: 0 36rpx 36rpx;
    }
  }
}

.full-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;

  &.bgf {
    background: url(../../static/bg1.png) #f8f8f8 no-repeat;
    background-size: 100% 100%;
  }
}

.answer-success {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  margin-top: -260rpx;
  .tip {
    font-size: 30rpx;
    color: #ff3333;
    font-weight: bold;
  }

  .venue-number {
    font-size: 60rpx;
    font-weight: bold;
    padding: 50rpx 0;
  }

  .cash-bg {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    .cash-bg-img {
      width: 600rpx;
      height: auto;
    }
    .cash {
      position: absolute;
      bottom: 0;
      left: 0;
      line-height: 208rpx;
      width: 600rpx;
      text-align: center;
      font-size: 90rpx;
      color: #fff;
      font-weight: bold;
    }
  }
  .tip-success {
    color: #13ce66;
    font-size: 40rpx;
    line-height: 1.8;
    font-weight: bold;
    margin-top: 30rpx;
  }
}
.line-down {
  text-decoration: underline;
  margin-top: 30rpx;
  font-size: 35rpx !important;
}
.preview-image-box {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  overflow: auto;
  display: flex;
  align-items: center;
  z-index: 10;
  .clear-icon {
    position: fixed;
    right: 0;
    top: 0;
    padding: 20rpx;
  }
  .preview-image {
    width: 100%;
    img {
      width: 100%;
    }
  }
  .mask {
    width: 100%;
    height: 100%;
    position: absolute;
    right: 0;
    top: 0;
    z-index: -1;
    background: rgba(0, 0, 0, 0.6);
    &.block {
      background: rgba(0, 0, 0, 1);
    }
  }
  .next {
    position: fixed;
    bottom: 130rpx;
    left: calc(375rpx - 150rpx);
    width: 300rpx;
    text-align: center;
    line-height: 80rpx;
    color: #fff;
    background: #ffc833;
    border-radius: 50rpx;
    font-weight: bold;
    font-size: 32rpx;
    &:active {
      opacity: 0.8;
    }
  }
}
.music-box {
  position: fixed;
  right: 20rpx;
  top: 10%;
  width: 40rpx;
  height: 40rpx;
  z-index: 1;
  border-radius: 50%;
  background: #fff;
  border: 1rpx solid #c2c2c2;
  padding: 15rpx;
  animation-duration: 3s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  &:active {
    background: #ccc;
  }
  img {
    width: 100%;
    height: 100%;
  }
  &.animations {
    animation-name: slidein;
  }
}
@keyframes slidein {
  0% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(90deg);
  }
  50% {
    transform: rotate(180deg);
  }
  75% {
    transform: rotate(270deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
